import 'dart:async';

import 'package:ble_printer/bean/ble_device.dart';
import 'package:ble_printer/ble_printer.dart';
import 'package:flutter/material.dart';
import 'package:kayo_package/kayo_package.dart';
import 'package:fluttertoast/fluttertoast.dart';

class KeySearchPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _KeySearchPageState();
}

class _KeySearchPageState extends State<KeySearchPage>
    with TickerProviderStateMixin {
  Timer? timer;

  bool play = true;
  List<BleDevice> devices = [];
  BleDevice? selectDevice;
  BleDevice? selectDevice2;
  bool? isBleConnected;
  bool finishAct = true;

  void cancelSearch() {
    if (play) {
      timer = Timer(Duration(seconds: 18), () {
        setState(() {
          play = !play;
        });
        BlePrinter.share.stopSearchBle();
      });
    }
  }

  @override
  void initState() {
    super.initState();
    play = true;
    devices.clear();
    selectDevice = null;

    BlePrinter.share.isBleConnected().then((value) {
      setState(() {
        isBleConnected = value;
      });
    });

    BaseSharedUtils.getBleDevice().then((data) {
      setState(() {
        selectDevice2 = data;
        if (null != selectDevice2?.mac && '' != selectDevice2?.mac) {
          finishAct = false;
          BlePrinter.share.connectBle(selectDevice2, autoOpenBle: false);
        }
      });
    });

    // BlePrinter.share.disconnectBle();

    BlePrinter.share.searchBle();
    cancelSearch();

    BlePrinter.share.initStateBle((data) {
      setState(() {
        var map = BlePrinter.share.getMapOrList(data);
        var type = map['type'];
        if (type == EventType.BLE_FOUND) {
          var bleRetData = BleRetData<List<BleDevice>>.fromJson(map, type);
          devices.clear();
          selectDevice = null;
          for (var i in bleRetData.data ?? []) {
            if (!BaseSysUtils.empty(i.name)) {
              devices.add(i);
            }
          }
        } else if (type == EventType.BLE_CONNECTED) {
          Fluttertoast.showToast(
              msg: "打印机联机成功",
              toastLength: Toast.LENGTH_LONG,
              gravity: ToastGravity.SNACKBAR,
              timeInSecForIosWeb: 2);
          if (finishAct != true) {
            setState(() {
              isBleConnected = true;
            });
            return;
          }
          if (null != selectDevice) {
            BaseSharedUtils.setBleDevice(selectDevice!);
          }
          Navigator.pop(context, selectDevice);
        } else if (type == EventType.BLE_CONNECTE_FAILED) {
          Fluttertoast.showToast(
              msg: "打印机连接失败",
              toastLength: Toast.LENGTH_LONG,
              gravity: ToastGravity.SNACKBAR,
              timeInSecForIosWeb: 2);
          setState(() {
            isBleConnected = false;
          });
        } else if (type == EventType.BLE_DISCONNECTED) {
          Fluttertoast.showToast(
              msg: "打印机断开连接",
              toastLength: Toast.LENGTH_LONG,
              gravity: ToastGravity.SNACKBAR,
              timeInSecForIosWeb: 2);
          setState(() {
            isBleConnected = false;
          });
        } else if (type == EventType.BLE_CONNECTE_NODEVICE) {
          Fluttertoast.showToast(
              msg: "没有找到打印机",
              toastLength: Toast.LENGTH_LONG,
              gravity: ToastGravity.SNACKBAR,
              timeInSecForIosWeb: 2);
          setState(() {
            isBleConnected = false;
          });
        } else if (type == EventType.BLE_ENABLE) {
          BlePrinter.share.connectBle(selectDevice2, autoOpenBle: false);
        } else if (type == EventType.BLE_DISABLE) {}
      });
    }, (error) {});
  }

  @override
  void dispose() {
    play = true;
    devices.clear();
    selectDevice = null;
    selectDevice2 = null;
    BlePrinter.share.stopSearchBle();
    timer?.cancel();
    BlePrinter.share.disposeBle();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ToolBar(
        elevation: 0,
        darkStatusText: true,
        iosBack: true,
        title: '连接打印机器',
        backgroundColor: Colors.white,
        actions: [
          play == true
              ? Center(
                  child: SizedBox(
                    child: CircularProgressIndicator(),
                    height: 30.0,
                    width: 30.0,
                  ),
                )
              : SizedBox(
                  height: 0,
                ),
          TextView(
            play == true ? '停止查找' : '开始查找',
            size: 13,
            radius: 10,
            color: Color(0xff333333),
            fontWeight: FontWeight.w600,
            alignment: Alignment.center,
            padding: EdgeInsets.only(left: 16, right: 16),
            onTap: () {
              _onTapSearch();
            },
          )
        ],
        child: Column(
          children: [
            selectDevice2?.mac == null || selectDevice2?.mac?.isEmpty == true
                ? Container()
                : Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      TextView(
                        '已绑定设备',
                        alignment: Alignment.centerLeft,
                        size: 14,
                        padding: EdgeInsets.only(left: 20),
                      ),
                      Container(
                        color: Colors.lightGreen.shade50,
                        padding: EdgeInsets.only(
                            left: 20, top: 12, bottom: 12, right: 20),
                        child: Row(
                          children: [
                            Expanded(
                                child: TextView(
                              selectDevice2?.name ?? '',
                            )),
                            TextView(
                              isBleConnected == true ? '已连接' : '未连接',
                              onTap: isBleConnected == true
                                  ? null
                                  : () {
                                      finishAct = false;
                                      BlePrinter.share
                                          .connectBle(selectDevice2);
                                    },
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
            TextView(
              '附近的设备',
              size: 14,
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.only(left: 20),
            ),
            Expanded(
                child: ListView(
              children: devices.map((e) {
                return e.mac == (selectDevice2?.mac ?? '')
                    ? Container()
                    : CardView(
                        margin: EdgeInsets.only(bottom: 1),
                        bgColors: [Colors.grey.shade100, Colors.grey.shade100],
                        onPressed: () {
                          selectDevice = e;
                          finishAct = true;
                          _onTapKey();
                        },
                        padding: EdgeInsets.only(
                            left: 20, right: 20, top: 12, bottom: 12),
                        child: TextView(
                          e.name,
                        ));
              }).toList(),
            ))
          ],
        ));
  }

  void _onTapKey() {
    setState(() {
      play = false;
    });
    BlePrinter.share.stopSearchBle();
    if (null != timer) {
      timer?.cancel();
    }
    BlePrinter.share.disconnectBle();
    BlePrinter.share.connectBle(selectDevice);
  }

  void _onTapSearch() {
    setState(() {
      play = !play;
    });
    if (null != timer) {
      timer?.cancel();
    }
    if (play) {
      cancelSearch();
      BlePrinter.share.searchBle();
    } else {
      BlePrinter.share.stopSearchBle();
    }
  }
}

// class AnimatedSpread extends AnimatedWidget {
//   final Tween<double> _opacityTween = Tween(begin: 1, end: 0);
//   final Tween<double> _radiusTween;
//   final Color color;
//
//   AnimatedSpread(
//       {Key? key,
//       required Animation<double> animation,
//       required double radius,
//       required double maxRadius,
//       required this.color})
//       : _radiusTween = Tween(begin: radius, end: maxRadius),
//         super(key: key, listenable: animation);
//
//   @override
//   Widget build(BuildContext context) {
//     final Animation<double> animation = listenable;
//     return Container(
//       width: _radiusTween.evaluate(animation),
//       width: _radiusTween.evaluate(animation),
//       height: _radiusTween.evaluate(animation),
//       child: ClipOval(
//         child: Opacity(
//           opacity: _opacityTween.evaluate(animation),
//           child: Container(
//             color: color,
//           ),
//         ),
//       ),
//     );
//   }
// }
